﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Marbles.Core.Content.Sites;
using System.IO;
using System.Xml;

namespace Marbles.Core.Content.SiteMap
{
    public class WebSiteMapWriter
    {

        public static string ContentType { get { return "text/xml"; } }

        private SiteDefinition _web = null;

        public WebSiteMapWriter(SiteDefinition Web)
        {
            _web = Web;
        }

        public WebSiteMapWriter()
        {
            _web = SiteDefinition.GetCurrent();
        }

        public void Save(WebSiteMap map, string filename)
        {
            FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
            Save(map, fs);
            fs.Flush();
            fs.Close();
        }

        public void Save(WebSiteMap map, Stream Stream)
        {
            XmlTextWriter writer = new XmlTextWriter(Stream, System.Text.ASCIIEncoding.UTF8);
            writer.WriteStartDocument(true);
            writer.WriteStartElement("", "siteMap", "http://schemas.microsoft.com/AspNet/SiteMap-File-1.0");

            foreach (WebSiteMapNode node in map)
            {
                CreateSiteMapNode(writer, node);
            }

            writer.WriteEndElement();
            writer.WriteEndDocument();
            writer.Flush();
        }

        private void CreateSiteMapNode(XmlTextWriter writer, WebSiteMapNode node)
        {
            writer.WriteStartElement("siteMapNode");
            writer.WriteAttributeString("url", node.Url);
            writer.WriteAttributeString("title", node.Title);
            writer.WriteAttributeString("description", node.Description);
            writer.WriteAttributeString("resourceKey", node.PageName.ToString());
            writer.WriteAttributeString("roles", "");

            if (node.HasChildren)
            {
                foreach (WebSiteMapNode child in node.ChildNodes)
                {
                    CreateSiteMapNode(writer, node);
                }
            }

            writer.WriteEndElement();
        }
    }
}